//
//  ZLPhotoLibrary.swift
//  ZLExtension
//
//  Created by 赵振磊 on 2025/1/20.
//

import Photos

public extension PHPhotoLibrary {
    /// 申请相册权限
    static func zl_requestAlbumAuthorization(completion: @escaping (PHAuthorizationStatus) -> Void) {
        let status = PHPhotoLibrary.authorizationStatus()
        if status == .authorized {
            completion(.authorized)
        } else {
            PHPhotoLibrary.requestAuthorization { status in
                DispatchQueue.main.async {
                    completion(status)
                }
            }
        }
    }
    
    /// 创建相册
    static func zl_createAlbum(name: String, completion: @escaping (Bool, Error?) -> Void) {
        PHPhotoLibrary.shared().performChanges({
            PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: name)
        }) { success, error in
            if success {
                completion(true, nil)
            } else {
                completion(false, error)
            }
        }
    }
    
    /// 获取相册
    static func zl_getAlbum(name: String, completion: @escaping (PHAssetCollection?) -> Void) {
        let fetchOptions = PHFetchOptions()
        let albums = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
        var assetCollection: PHAssetCollection?
        for i in 0..<albums.count {
            if albums.object(at: i).localizedTitle == name {
                assetCollection = albums.object(at: i)
                break
            }
        }
        completion(assetCollection)
    }
    
    /// 获取或创建相册
    static func zl_getOrCreateAlbum(name: String, completion: @escaping (PHAssetCollection?) -> Void) {
        self.zl_getAlbum(name: name) { collection in
            if collection != nil {
                completion(collection)
                return
            }
            self.zl_createAlbum(name: name) { success, error in
                if !success {
                    completion(nil)
                    return
                }
                self.zl_getAlbum(name: name) { collection in
                    completion(collection)
                }
            }
        }
    }
}
